import { useState, useEffect } from 'react'
import style from './index.module.scss'
import { GetGoodsFnc } from '@/api/goods' 
import { Breadcrumb, Row, Col, Input, Button } from "antd"
import Tables from './components/Tables/index'
import EditGoods from './components/Edit'
import useSyncState from '@/utils/tongbu'
import { useNavigate } from 'react-router-dom'

const Goods = () => {
  const { Search } = Input  
  const navigate = useNavigate()
  const [dataSource, setDataSource] = useState([])  // table数据源
  const [pageNow, setPageNow] = useSyncState(1)
  const [pageSize, setPageSize] = useState(2)
  const [total, setTotal] = useState(0)
  const [ipt, setIpt] = useState('') // 输入框输入的内容
  const [editBox, setEditBox] = useState(false) // 修改商品的盒子
  const [goodsID, setGoodsID] = useState('') // 商品ID

  // 数据初始化
  const init = async (iptValue: string, pageNow: number, pageSize: number) => {
    const res = await GetGoodsFnc({query: iptValue, pagenum: pageNow, pagesize: pageSize})
    setIpt(iptValue)
    if(res.data.meta.status === 200) {
      let arr = res.data.data.goods.map((item: any, index: number) => {
        return {
          key: index + 1,
          id: item.goods_id,
          goods_name: item.goods_name,
          goods_price: item.goods_price,
          goods_weight: item.goods_weight,
          add_time: item.add_time
        }
      })
      setDataSource(arr)
      setTotal(res.data.data.total)
    }
  }
  useEffect(() => { init(ipt, pageNow, pageSize) }, [])

  // 更改每页数量 或者 切换当前页 给子组件使用
  const sizeCurrentChange = (current: number, pageSize: number) => {
    setPageNow(current)
    setPageSize(pageSize)
    init(ipt, current, pageSize)
  }

  // 编辑盒子的 显示 与 隐藏  给子组件使用
  const changeEditBox = async (flag: boolean, ...id: string[]) => {
    setEditBox(flag)
    setGoodsID(id[0])
  }

  // 删除用户, 给子组件使用, 当前页只有一条数据的时候, 删完应该返回上一页
  const changePageNow = () => {
    setPageNow(pageNow - 1, (data: number) => {
      init(ipt, data, pageSize)
    })
  }

  return (
    <>
      <Breadcrumb items={[{ title: '商品管理' }, { title: '商品列表' }]} />

      <div className={style.goodsContent}>
        {/* 搜索框 */}
        <Row gutter={20} className={style.search}>
          <Col span={5}>
            <Search placeholder="输入内容" size="large" onSearch={(value: string) => init(value, 1, pageSize)} allowClear/>
          </Col>
          <Col span={4}>
            <Button type='primary' size="large" onClick={() => navigate('/addGoods')}>添加商品</Button>
          </Col>
        </Row>

        {/* 表格 */}
        <Tables dataSource={dataSource} init={init} ipt={ipt} current={pageNow} pageSize={pageSize} total={total} sizeCurrentChange={sizeCurrentChange} changeEditBox={changeEditBox} changePageNow={changePageNow}/>

        {/* 修改商品盒子 */}
        <EditGoods editBox={editBox} changeEditBox={changeEditBox} goodsID={goodsID} init={init} current={pageNow} pageSize={pageSize} ipt={ipt}/>
      </div>
    </>
  )
}

export default Goods